package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

type Data struct {
	user     string `json:"Login.Token1"`
	password string `json:"Login.Token2"`
}
type selfInfo struct {
	ID            string `json:"XGH_566872"` //学号
	Password      string //密码
	Name          string `json:"XM_140773"`     //姓名
	IDCard        string `json:"SFZJH_402404"`  // 身份证
	School        string `json:"SZDW_439708"`   //学院
	Major         string `json:"ZY_878153"`     //专业
	GDXW_926421   string `json:"GDXW_926421"`   //硕士生
	Mentor        string `json:"DSNAME_606453"` //导师
	PYLB_253720   string `json:"PYLB_253720"`   // 定向or非定向
	SELECT_172548 string `json:"SELECT_172548"` //宿舍  例如：常州校区08号楼乙
	TEXT_91454    string `json:"TEXT_91454"`    //门牌号
	TEXT_24613    string `json:"TEXT_24613"`    //电话
	TEXT_826040   string `json:"TEXT_826040"`   //紧急联系人电话
}

// healthyClock 打卡上报
func healthyClock(cookies []*http.Cookie, id, newData string) error {
	client := &http.Client{}
	req, _ := http.NewRequest("POST", "http://dailyreport.hhu.edu.cn/pdc/formDesignApi/dataFormSave?wid=A3359E1B43376F77E0538101600A8722&userId="+id, bytes.NewReader([]byte(newData)))
	for _, v := range cookies {
		if v==nil{
			return errors.New("cookie 为空")
		}
		req.AddCookie(&http.Cookie{
			Name:   v.Name,
			Value:  v.Value,
			Domain: v.Domain,
			Path:   v.Path,
		})
	}
	req.Header.Add("Accept", "application/json, text/javascript, */*; q=0.01")
	req.Header.Add("Accept-Language", "zh-CN,zh;q=0.9")
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	rsp, err := client.Do(req)
	if err != nil {
		return err
	}
	body, _ := ioutil.ReadAll(rsp.Body)
	if strings.Contains(string(body), "true") {
		return nil
	}
	return errors.New(fmt.Sprintf("打卡失败 %s", string(body)))

}

// getCookie 登录
func getCookie(data Data) ([]*http.Cookie, error) {
	dataJson, _ := json.Marshal(data)
	response, err := http.Post("http://ids.hhu.edu.cn/amserver/UI/Login", "application/x-www-form-urlencoded", bytes.NewBuffer(dataJson))
	return response.Cookies(), err
}

// getInfo 打卡内容
func getInfo(edcsonliu selfInfo) string {
	now := time.Now()                     //获取当前时间
	year := fmt.Sprintf("%d", now.Year()) //年
	month := fmt.Sprintf("%d", now.Month())
	if now.Month() < 10 {
		month = fmt.Sprintf("0%d", now.Month())
	}
	day := fmt.Sprintf("%d", now.Day())
	if now.Day() < 10 {
		day = fmt.Sprintf("0%d", now.Day())
	}

	newData := fmt.Sprintf("DATETIME_CYCLE=%s/%s/%s", year, month, day) +
		fmt.Sprintf("&XGH_566872=%s&XM_140773=%s&SFZJH_402404=%s&SZDW_439708=%s&ZY_878153=%s&GDXW_926421=%s&DSNAME_606453=%s&PYLB_253720=%s&SELECT_172548=%s&TEXT_91454=%s&TEXT_24613=%s&TEXT_826040=%s&",
			edcsonliu.ID, edcsonliu.Name, edcsonliu.IDCard, edcsonliu.School, edcsonliu.Major, edcsonliu.GDXW_926421, edcsonliu.Mentor, edcsonliu.PYLB_253720, edcsonliu.SELECT_172548, edcsonliu.TEXT_91454, edcsonliu.TEXT_24613, edcsonliu.TEXT_826040) +
		"RADIO_799044=正常（37.3℃）&RADIO_384811=校内&RADIO_907280=健康&RADIO_716001=健康&RADIO_248990=否"
	return newData
}

// GetUser 获取打卡人员
func GetUser() map[selfInfo]bool {
	users := map[selfInfo]bool{}
	return users
}

func main() {
	users := GetUser()
	for {
		now := time.Now() //获取当前时间
		if now.Hour() == 9 {
			for k := range users {
				users[k] = false
			}
		}
		for k, v := range users {
			if v {
				continue
			}
			cookie, err := getCookie(Data{user: k.ID, password: k.Password})
			if err != nil {
				fmt.Printf("%s  %s 打卡失败  getCookie error\n", time.Now().Format("2006-01-02 15:04:05"), k.Name)
				continue
			}
			info := getInfo(k)
			for i:=0;i<5;i++{
				if err = healthyClock(cookie, k.ID, info); err == nil {
					fmt.Printf("%s  %s 打卡成功\n", time.Now().Format("2006-01-02 15:04:05"), k.Name)
					users[k] = true
					break
				} else {
					fmt.Printf("%s  %s 打卡失败  healthyClock error\n", time.Now().Format("2006-01-02 15:04:05"), k.Name)
				}
			}
		}
		time.Sleep(time.Hour)
	}
}
